/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import bmg.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBElement;
import model.Order;
import model.ShoppingCart;
import com.google.gson.Gson;

/**
 *
 * @author Cranberry
 */
public class Facade extends HttpServlet
{

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        String errors = "";

        // we get the session
//        ShoppingCart cart;
        HttpSession session = request.getSession(true);
//        if(session.isNew())
//        {
//            ShoppingCart cart = new ShoppingCart(); 
//            ObjectFactory factory = new ObjectFactory();
//            JAXBElement<String> firstname = factory.createCustomerFirstName("Inconnu");
////            cart.getCustomer().setFirstName(firstname);
//            Customer customer = new Customer();
//            customer.setFirstName(firstname);
//            cart.setCustomer(customer);
//            session.setAttribute("cart", cart);
//        }

//        cart = (ShoppingCart)session.getAttribute("cart");

//        request.setAttribute("cart", cart);

        // we get the "action" in the get parameter
        String action = request.getParameter("action");

        /**
         * Récupère les catégories sans arrêt, étant donné qu'elles sont toujours affichées
         */
        List<Category> categories = new ArrayList<Category>();
        try
        {
            categories = getCategories().getCategory();
        }
        catch (Exception e)
        {
            errors = "Une erreur est survenue. <br>Message : " + e.getMessage() + ".";
            request.setAttribute("errors", errors);
            RequestDispatcher view = request.getRequestDispatcher("404.jsp");
            view.forward(request, response);
        }
        request.setAttribute("categories", categories);

        /**
         * "Switch" qui redirige le visiteur selon l'action en cours
         */
        /**
         * Page d'accueil
         */
        if (action == null)
        {
            List<Product> last_products = new ArrayList<Product>();
            
            Customer customer = new Customer();
            ObjectFactory factory = new ObjectFactory();
            JAXBElement<String> firstname = factory.createCustomerFirstname("Glabah");
            customer.setFirstname(firstname);
            String temp = "coucou";
            
            try
            {
                last_products = getLastProducts().getProduct();
                temp = saveCustomer(customer);
            }
            catch (Exception e)
            {
                errors = "Une erreur est survenue. <br>Message : " + e.getMessage() + ".";
                request.setAttribute("errors", errors);
                RequestDispatcher view = request.getRequestDispatcher("404.jsp");
                view.forward(request, response);
            }
            
            request.setAttribute("last_products", last_products);
            request.setAttribute("temp", temp);
            RequestDispatcher view = request.getRequestDispatcher("index.jsp");
            view.forward(request, response);
        }
        /**
         * Affichage de la liste des produits de la catégorie sélectionnée
         */
        else if(action.equals("show_category"))
        {
            // Récupère le category_id passé en GET
            String category_id = request.getParameter("category_id");
            // Gère le cas ou aucune id n'est trouvée
            if(category_id == null)
            {
                errors = "Une erreur est survenue : aucune catégorie n'a été demandée.";
                request.setAttribute("errors", errors);
                RequestDispatcher view = request.getRequestDispatcher("404.jsp");
                view.forward(request, response);
            }
            
            // Vérifie que l'id entrée est bien un nombre
            int id = 0;
            try 
            {
                id = Integer.parseInt(category_id);
            } 
            catch (Exception e) 
            {
                errors = "Une erreur est survenue. Veuillez entrer un nombre pour affiehr une catégorie.";
                request.setAttribute("errors", errors);
                RequestDispatcher view = request.getRequestDispatcher("404.jsp");
                view.forward(request, response);
            }
            // Récupère les informations sur la catégorie en cours
            // ainsi que les produits liés à cette catégorie
            Category current_category = null;
            List<Product> products = null;
            try 
            {
                products = getProductsFromCategory(id).getProduct();
                current_category = getCurrentCategory(id);
            } 
            catch (Exception e)
            {
                errors = "Une erreur est survenue. <br>Message : " + e.getMessage() + ".";
                request.setAttribute("errors", errors);
                RequestDispatcher view = request.getRequestDispatcher("404.jsp");
                view.forward(request, response);
            } 
            
            request.setAttribute("products", products);
            request.setAttribute("current_category", current_category);
            RequestDispatcher view = request.getRequestDispatcher("category.jsp");
            view.forward(request, response);
        }
        /**
         * Fiche d'un produit
         */
        else if(action.equals("show_product"))
        {
            // Récupère l'id du produit
            String product_id = request.getParameter("product_id");
            if(product_id == null)
            {
                errors = "Une erreur est survenue : aucun produit n'a été demandé.";
                request.setAttribute("errors", errors);
                RequestDispatcher view = request.getRequestDispatcher("404.jsp");
                view.forward(request, response);
            }
            
            // Vérifie que l'id entrée est bien un nombre
            int id = 0;
            try 
            {
                id = Integer.parseInt(product_id);
            } 
            catch (Exception e) 
            {
                errors = "Une erreur est survenue. Veuillez entrer un nombre pour affiehr un produit.";
                request.setAttribute("errors", errors);
                RequestDispatcher view = request.getRequestDispatcher("404.jsp");
                view.forward(request, response);
            }
            Product product = null;
            Category current_category = null;
            try 
            {
                categories = getCategories().getCategory();
                product = getProduct(id);
                if(product == null)
                {
                    errors = "Une erreur est survenue. Aucun produit ne correspond à cette requête.";
                    request.setAttribute("errors", errors);
                    RequestDispatcher view = request.getRequestDispatcher("404.jsp");
                    view.forward(request, response);
                }
                current_category = getCurrentCategory(product.getCategoryID());
            } 
            catch (Exception e)
            {
                errors = "Exception rencontrée. <br>Erreur : " + e.getMessage() + ". <br>Localized message : " + e.getLocalizedMessage() + "<br />Cause : "+e.getCause();
            } 
            
            request.setAttribute("current_category", current_category);
            request.setAttribute("product", product);
            RequestDispatcher view = request.getRequestDispatcher("product.jsp");
            view.forward(request, response);
        }
        /**
         * Ajoute un produit au panier
         */
//        else if(action.equals("add_basket"))
//        {
//            String product_id = request.getParameter("product_id");
//            if(product_id == null) // FIXME
//            {
//                errors = "Une erreur est survenue : aucun produit n'a été commandé.";
//                request.setAttribute("errors", errors);
//                RequestDispatcher view = request.getRequestDispatcher("404.jsp");
//                view.forward(request, response);
//            }
//            int id = 0;
//            try 
//            {
//                id = Integer.parseInt(product_id);
//            } 
//            catch (Exception e) 
//            {
//                errors = "Une erreur est survenue. Veuillez entrer un nombre pour affiehr un produit.";
//                request.setAttribute("errors", errors);
//                RequestDispatcher view = request.getRequestDispatcher("404.jsp");
//                view.forward(request, response);
//            }
//            Product product = null;
//            try 
//            {
//                categories = getCategories().getCategory();
//                product = getProduct(id);
//                if(product == null)
//                {
//                    errors = "Une erreur est survenue. Aucun produit ne correspond à cette requête.";
//                    request.setAttribute("errors", errors);
//                    RequestDispatcher view = request.getRequestDispatcher("404.jsp");
//                    view.forward(request, response);
//                }
//            } 
//            catch (Exception e)
//            {
//                errors = "Exception rencontrée. <br>Erreur : " + e.getMessage() + ". <br>Localized message : " + e.getLocalizedMessage() + "<br />Cause : "+e.getCause();
//            } 
//            ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
//            ObjectFactory factory = new ObjectFactory();
//            JAXBElement<String> firstname = factory.createCustomerFirstname("Glabah");
//            cart.getCustomer().setFirstname(firstname);
//            
//            
//            // check if product already in list
//            List<Order> orders_cart = cart.getOrders();
//            boolean to_add = true;
//            
//            for(Order o : orders_cart)
//            {
//                if(o.getProduct().getID() == product.getID())
//                {
//                    o.setQuantity(o.getQuantity()+1);
//                    to_add = false;
//                }
//            }
//            
//            if(to_add)
//            {
//                Order order = new Order();
//                order.setProduct(product);
//                order.setQuantity(1);
//                cart.getOrders().add(order);
//            }
//            
//            
//            
//            session.setAttribute("cart", cart);
//            request.setAttribute("categories", categories);
//            response.sendRedirect("?action=show_category&id=1");
//        }
//        else if(action.equals("show_cart"))
//        {
//            List<Category> categories = new ArrayList<Category>();
//            String product_id = request.getParameter("product_id");
//            if(product_id == null) // FIXME
//            {
//                // do something
//            }
//            int id = 0;
//            try 
//            {
//                id = Integer.parseInt(product_id);
//            } 
//            catch (Exception e) 
//            {
//            }
//            Product product = null;
//            try 
//            {
//                categories = getCategories().getCategory();
//                product = getProduct(id);
//                if(product == null)
//                    errors = "BLAAAAh";
//                else
//                    errors = "GOOOOH";
//            } 
//            catch (Exception e)
//            {
//                errors = "Exception rencontrée. <br>Erreur : " + e.getMessage() + ". <br>Localized message : " + e.getLocalizedMessage() + "<br />Cause : "+e.getCause();
//            } 
//            
//            request.setAttribute("categories", categories);
//            RequestDispatcher view = request.getRequestDispatcher("shopping_cart.jsp");
//            view.forward(request, response);
//        }
//        else if(action.equals("order"))
//        {
//            List<Category> categories = new ArrayList<Category>();
//            String product_id = request.getParameter("product_id");
//            if(product_id == null) // FIXME
//            {
//                // do something
//            }
//            int id = 0;
//            try 
//            {
//                id = Integer.parseInt(product_id);
//            } 
//            catch (Exception e) 
//            {
//            }
//            Product product = null;
//            try 
//            {
//                categories = getCategories().getCategory();
//                product = getProduct(id);
//                if(product == null)
//                    errors = "BLAAAAh";
//                else
//                    errors = "GOOOOH";
//            } 
//            catch (Exception e)
//            {
//                errors = "Exception rencontrée. <br>Erreur : " + e.getMessage() + ". <br>Localized message : " + e.getLocalizedMessage() + "<br />Cause : "+e.getCause();
//            } 
//            
//            request.setAttribute("categories", categories);
//            RequestDispatcher view = request.getRequestDispatcher("order.jsp");
//            view.forward(request, response);
//        }
//        else if(action.equals("validate_order"))
//        {
//            List<Category> categories = new ArrayList<Category>();
//            
//            // get every data from the form
//            String name = (String) request.getAttribute("name");
//            String firstname = (String) request.getAttribute("firstname");
//            String mail = (String) request.getAttribute("mail");
//            String number = (String) request.getAttribute("number");
//            String street = (String) request.getAttribute("street");
//            String zip = (String) request.getAttribute("zip");
//            String city = (String) request.getAttribute("city");
//            String type = (String) request.getAttribute("type");
//            
//            ObjectFactory factory = new ObjectFactory();
//            JAXBElement<String> cus_firstname = factory.createCustomerFirstName(firstname);
//            JAXBElement<String> cus_name = factory.createCustomerFirstName(name);
//            Customer customer = new Customer();
//            customer.setFirstName(cus_firstname);
//            customer.setName(cus_name);
//            
//            Gson gson = new Gson();
//            try {
//                String jsonCustomer = gson.toJson(customer, Customer.class);
//            } catch (Exception e) {
//                errors = "Exception rencontrée. <br>Erreur : " + e.getMessage() + ". <br>Localized message : " + e.getLocalizedMessage() + "<br />Cause : "+e.getCause();
//            }
//            
//            
////            Map<String, String> customer = new HashMap();
////            customer.put("name", name);
////            customer.put("firstname", firstname);
////            customer.put("mail", mail);
////            customer.put("number", number);
////            customer.put("street", street);
////            customer.put("zip", zip);
////            customer.put("city", city);
////            customer.put("type", type);
//            
//            ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
//            
//            
////            Map<Integer, Product> orders = new HashMap();
////            for(Order o : cart.getOrders())
////            {
////                orders.put(o.getQuantity(), o.getProduct());
////            }
//            String bla = "Raté !";
//            try 
//            {
////                saveOrders(customer, orders);
////                bla = saveCustomer(jsonCustomer);
//                
//            }
//            catch (Exception e) 
//            {
//                errors = "Exception rencontrée. <br>Erreur : " + e.getMessage() + ". <br>Localized message : " + e.getLocalizedMessage() + "<br />Cause : "+e.getCause();
//            }
//            
//            request.setAttribute("errors", errors);
//            request.setAttribute("categories", categories);
//            request.setAttribute("bla", bla);
//            RequestDispatcher view = request.getRequestDispatcher("index.jsp");
//            view.forward(request, response);
//        }


//        int result = 0;
//        String errors = "No error";
//        Category category = null;
//        Category category = null;
//        List<Category> categories = new ArrayList<Category>();
//        String temp = "Rien";
//        List<Category> categories = new ArrayList<Category>();
//        try 
//        {
//            result = doWork(8, 2);
//            category = getCategory();
//            temp = category.getName().getValue();
//            categories = getCategories().getCategory();
//            temp = categories.get(1).getName().getValue();
//            categories = getCategories().getCategory();
//        } 
//        catch (Exception e)
//        {
//            errors = "Exception rencontrée. <br>Erreur : " + e.getMessage() + ". <br>Localized message : " + e.getLocalizedMessage() + "<br />Cause : "+e.getCause();
//        } 
//        finally
//        {
//            
//        }

//        request.setAttribute("result", result);
        request.setAttribute("errors", errors);
//        request.setAttribute("category", category);
//        request.setAttribute("categories", categories);
//        request.setAttribute("temp", temp);
//        request.setAttribute("categories", categories);
//        request.setAttribute("testcat", testcat);
//        request.setAttribute("hello", hello);
//        request.setAttribute("life", lifeanswer);


        // SESSION TEST
//        String action = request.getParameter("action");
//        
//        request.setAttribute("test", action);




//        String action = "";
//        if(request.getAttribute("action") != null)
//            action = request.getAttribute("action").toString();
//        HttpSession session = request.getSession();
//        
//        if(null != action && action.equals("addbasket"))
//        {
//            session.setAttribute("panier", "un produit acheté !");
//        }
//        else if(null != action && action.equals("removebasket"))
//        {
//            session.setAttribute("panier", "z'avez rien acheté !");
//        }
//        
//        if(session.isNew())
//        {
//            request.setAttribute("session", "Bienvenue !");
//            session.setAttribute("username", "Cranberry");
//        }
//        else
//        {
//            String username = session.getAttribute("username").toString();
//            String panier = "";
//            if(session.getAttribute("panier") != null)
//                panier = session.getAttribute("panier").toString();
//            panier = (null == panier) ? "rien" : panier;
//            request.setAttribute("session", "Bon retour "+username+" ! Contenu du panier : "+panier);
//        }



//        RequestDispatcher view = request.getRequestDispatcher("index.jsp");
//        view.forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo()
    {
        return "Short description";
    }// </editor-fold>

    private static ArrayOfCategory getCategories()
    {
        org.tempuri.BMGService service = new org.tempuri.BMGService();
        org.tempuri.IBMGService port = service.getBasicHttpBindingIBMGService();
        return port.getCategories();
    }

    private static Category getCurrentCategory(java.lang.Integer categoryId)
    {
        org.tempuri.BMGService service = new org.tempuri.BMGService();
        org.tempuri.IBMGService port = service.getBasicHttpBindingIBMGService();
        return port.getCurrentCategory(categoryId);
    }

    private static ArrayOfProduct getLastProducts()
    {
        org.tempuri.BMGService service = new org.tempuri.BMGService();
        org.tempuri.IBMGService port = service.getBasicHttpBindingIBMGService();
        return port.getLastProducts();
    }

    private static ArrayOfProduct getProductsFromCategory(java.lang.Integer categoryId)
    {
        org.tempuri.BMGService service = new org.tempuri.BMGService();
        org.tempuri.IBMGService port = service.getBasicHttpBindingIBMGService();
        return port.getProductsFromCategory(categoryId);
    }

    private static Product getProduct(java.lang.Integer productId)
    {
        org.tempuri.BMGService service = new org.tempuri.BMGService();
        org.tempuri.IBMGService port = service.getBasicHttpBindingIBMGService();
        return port.getProduct(productId);
    }

    private static String saveCustomer(bmg.Customer customer)
    {
        org.tempuri.BMGService service = new org.tempuri.BMGService();
        org.tempuri.IBMGService port = service.getBasicHttpBindingIBMGService();
        return port.saveCustomer(customer);
    }

 


    
}
